<?php

namespace IDock\Insurance\AMIC\Response;

use IDock\Http\Response;
use IDock\IDock\IDockEnums;
use IDock\Insurance\AMIC\AMICEnums;
use IDock\Printer\NonCar\NonCarInquiryPrinter;
use IDock\Printer\NonCar\NonCarInquirySinglePrinter;
use IDock\Printer\Premium\PremiumBIPrinter;
use IDock\Printer\Premium\PremiumCoveragePrinter;
use IDock\Printer\Premium\PremiumInquiryPrinter;
use IDock\Printer\SpecialClausesPrinter;

class PremiumInquiryResponse extends AllAMICResponse
{

    public function resolve(): Response
    {
        $body = $this->getBody();
        $body = iconv('GBK', 'UTF-8//IGNORE', $body);

        if ($this->printer) {
            $this->printer = new $this->printer;
        }
        if ($body) {
            $xml = simplexml_load_string($body);
            $body = $this->objectToArray($xml);
            $returnCode = $body['Head']['returnCode'] ?? '';
            $message = $body['Head']['returnMsg'] ?? '';
            $this->setBody($body);
            if ($returnCode != '0000') {
                $this->setError($message);
                return $this;
            }
        }

        return $this;
    }

    /**
     * @var PremiumInquiryPrinter $printer
     * @var  $printer
     */
    public $printer = PremiumInquiryPrinter::class;

    protected $records = [];

    protected $result = [];

    public $planCode = '';

    public $productCode = '';

    public $insuredNum = 1;

    public function printerInit(): Response
    {
        if (!$this->printer->success) {
            return $this;
        }
        $body = $this->getBody()['Body'] ?? [];
        $ciMsg = $body['qtnBase']['platReturnMsgCI'] ?? '';
        $biMsg = $body['qtnBase']['platReturnMsgBusi'] ?? '';
        if (!empty($ciMsg) or !empty($biMsg)) {
            if (strpos($ciMsg, '重复投保') !== false or strpos($biMsg, '重复投保') !== false) {
                $this->repeat($ciMsg, $biMsg);
                if ($this->printer->repeatInsuredFlg) {
                    $this->printer->success = false;
                    $this->printer->repeatMessage = $ciMsg . ' ' . $biMsg;
                    return $this;
                }
            }
            $this->setError($biMsg . "\n" . $ciMsg);
            $this->printer->success = false;
            return $this;
        }
        //询价流程号
        $mainData = $body['qtnBase'] ?? [];

        //车船税
        if ($carShipTax = $body['vehicleTaxation'] ?? '') {
            $this->printer->carTaxPrinter->carShipTax = $carShipTax['sumTax'] ?? '';
            $this->printer->carTaxPrinter->overdue = $carShipTax['sumOverdue'] ?? '';
            $this->printer->carTaxPrinter->thisYearTax = $carShipTax['annualTaxDue'] ?? '';
            $this->printer->argc['carShipTax'] = $this->printer->carTaxPrinter->carShipTax;
        }
        $reNewType = ['0' => '新保', '1' => '续保', '2' => '转保'];
        $ciData = $body['applicationCI'] ?? '';
        $this->printer->inquiryNo = $mainData['orderNo'] ?? '';//mainSlipNo
        //交强险
        $this->printer->ciPremiumPrinter->ciPremium = $ciData['expectPrm'] ?? '';
        $this->printer->ciPremiumPrinter->ciBasePremium = $ciData['basedPremium'] ?? '';
        $this->printer->ciPremiumPrinter->ciDiscount = $ciData['discount'] ?? '';
        $this->printer->ciPremiumPrinter->ciStartData = $ciData['effectiveDate'] ? date('Y-m-d H:i:s', strtotime($ciData['effectiveDate'])) : '';
        $this->printer->ciPremiumPrinter->ciEndData = $ciData['expireDate'] ? date('Y-m-d H:i:s', strtotime($ciData['expireDate'])) : '';
        $this->printer->premiumFactorPrinter->TCIFactorAppend('连续承保出险次数', 'claimTimes', $ciData['claimTimes'] ?? '');
        $this->printer->premiumFactorPrinter->TCIFactorAppend('理赔浮动原因码', 'claimAdjustReason', AMICEnums::$adjustCodeCi[$ciData['claimAdjustReason'] ?? ''] ?? '');
        $this->printer->premiumFactorPrinter->TCIFactorAppend('不浮动原因', 'noClaimAdjustReason', AMICEnums::$noAdjustCodeCi[$ciData['noClaimAdjustReason'] ?? ''] ?? '');
        $this->printer->premiumFactorPrinter->TCIFactorAppend('交强险忠诚度', 'isNewIns', $reNewType[$ciData['isNewIns'] ?? ''] ?? '');
        //忠诚度
        $this->printer->argc['CIRenewalType'] = $this->getRenewalType($ciData['isNewIns'] ?? '');
        $this->printer->ciInquiryNo = $ciData['proposalNoCI'] ?? '';
        $this->printer->argc['ciPremium'] = $this->printer->ciPremiumPrinter->ciPremium;
        $this->printer->argc['orderNo'] = $this->printer->inquiryNo;

        $riskArr = $body['busiCoverageItemList']['busiCoverageItem'] ?? [];
        $biData = $body['applicationBusi'] ?? '';
        $this->printer->biPremiumPrinter = new PremiumBIPrinter();
        $this->printer->biPremiumPrinter->biPremium = $biData['expectPrm'];
        $this->printer->biPremiumPrinter->biBasePremium = $biData['basedPremium'] ?? '';
        $this->printer->biPremiumPrinter->biStartData = $biData['effectiveDate'] ? date('Y-m-d H:i:s', strtotime($biData['effectiveDate'])) : '';
        $this->printer->biPremiumPrinter->biEndData = $biData['expireDate'] ? date('Y-m-d H:i:s', strtotime($biData['expireDate'])) : '';
        $this->printer->biPremiumPrinter->biDiscount = $biData['discount'] ?? '';
        $this->printer->biInquiryNo = $biData['proposalNoBI'] ?? '';
        $this->printer->argc['biPremium'] = $this->printer->biPremiumPrinter->biPremium;


        $this->printer->premiumFactorPrinter->VCIFactorAppend('整单建议折扣', 'adviceDiscount', $biData['adviceDiscount'] ?? '');
        $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优浮动原因', 'claimAdjustReason', AMICEnums::$adjustCodeBi[$biData['claimAdjustReason'] ?? ''] ?? '');
        $this->printer->premiumFactorPrinter->VCIFactorAppend('无赔优不浮动原因', 'noClaimAdjustReason', AMICEnums::$noAdjustCodeBi[$biData['noClaimAdjustReason'] ?? ''] ?? '');
        $this->printer->premiumFactorPrinter->VCIFactorAppend('连续承保出险次数', 'claimTimes', $biData['claimTimes'] ?? 0);
        $this->printer->premiumFactorPrinter->VCIFactorAppend('商业险忠诚度', 'isNewIns',  $reNewType[$biData['isNewIns'] ?? ''] ?? '');
        $this->printer->argc['BIRenewalType'] = $this->getRenewalType($biData['isNewIns'] ?? '');
        $vehicle = $body['vehicle'] ?? [];
        $this->printer->premiumFactorPrinter->ComFactorAppend('家用车风险等级', 'marginalCostGrade', $vehicle['marginalCostGrade'] ?? '');
        $this->printer->premiumFactorPrinter->ComFactorAppend('协商价上下限', 'carMarketPriceLimit', $vehicle['carMarketPriceLimit'] ?? '');
        //险种
        $riskArr = $this->formatArray($riskArr);
        if (!empty($riskArr)) foreach ($riskArr as $kind) {
            $coverage = new PremiumCoveragePrinter();
            if (!empty($kind['coverageCode'])) {
                $coverage->coverageCode = array_search($kind['coverageCode'], AMICEnums::$coverageCode);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode] ?? '';
                $coverage->premium = $kind['expectPrm'] ?? '';
                $coverage->amount = $kind['sumAmount'] ?? '';
                $this->printer->coverageListAppend($coverage);
            }
        }
        //非车
        $this->printer->argc['nonCarFee'] = $body['appliHealthInsList']['appliHealthIns']['expectPrm'] ?? 0;
        //特约
        $specialClause = $body['appClauseList']['appClause'] ?? [];
        //系数
        if ($biData['discountDesc'] ?? '') {
            $discountDesc = str_replace(' ', '', $biData['discountDesc']);
            preg_match('/无赔优待系数([\d\.]+)/', $discountDesc, $matches);
            if ($matches and isset($matches[1])) {
                $this->printer->ncdFactor = $matches[1];
            }

            preg_match('/自主定价系数([\d\.]+)/', $discountDesc, $matches2);
            if ($matches2 and isset($matches2[1])) {
                $this->printer->premiumFactorPrinter->VCIFactorAppend('自主定价系数', 'selfPricingCoef', $matches2[1]);
            }
        }

        foreach ($specialClause as $value) {
            $specialClauses = new SpecialClausesPrinter();
            $specialClauses->clauseCode = $value['clauseCode'] ?? '';
            $specialClauses->clauseName = $value['clausesName'] ?? '';
            $specialClauses->clauseContent = $value['context'] ?? '';
            if ($value['clauseType'] == 'B') {
                //商业险
                $specialClauses->riskType = 'VCI';
            } else if ($value['clauseType'] == 'C') {
                $specialClauses->riskType = 'TCI';
            } elseif ($value['clauseType'] == 'H') {
                $specialClauses->riskType = 'NC';
            }
            $specialClauses->autoFlag = $value['delFlag'] ? '0' : '1';
            $this->printer->specialClausesAppend($specialClauses);
        }
        return $this;
    }

    private function getRenewalType($typeCode)
    {
        switch ($typeCode){
            case 0:
                return '新';
            case 1:
                return '续';
            case 2:
                return '转';
        }
        return '';
    }

    public function formatArray($arr): array
    {
        if (empty($arr)) return [];
        if (!is_array($arr)) {
            return [];
        }
        if (!isset($arr[0])) {
            $tmp = $arr;
            unset($arr);
            $arr[] = $tmp;
        }
        return $arr;
    }

    /**
     * 重复投保
     * @param $ciMsg
     * @param $biMsg
     */
    public function repeat($ciMsg, $biMsg)
    {
        if (preg_match('/终保日期 ([\d\s:-]+)/', $ciMsg, $matches)) {
            if ($matches[1] ?? '') {
                $ciStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['ciStartData'] = $ciStartData;
                $this->printer->repeatInsuredFlg = true;
            }
        }


        if (preg_match('/终保日期：([\d\s:-]+)/', $biMsg, $matches)) {
            if ($matches[1] ?? '') {
                $biStartData = date('Y-m-d H:i:s', strtotime($matches[1]));
                $this->printer->repeatInsurePrinter['biStartData'] = $biStartData;
                $this->printer->repeatInsuredFlg = true;
            }
        }
    }

    public function buildCoverage($isEnergy, array $orgList)
    {
        $orgList = array_combine(array_column($orgList, 'coverageCode'), $orgList);

        foreach ($this->printer->coverageList as &$coverage) {
            /*** @var $coverage PremiumCoveragePrinter */

            if ($isEnergy) {
                $coverage->coverageCode = 'C1' . substr($coverage->coverageCode, 2, 4);
                $coverage->coverageName = IDockEnums::$coverageCode[$coverage->coverageCode];
            }

            if (!$coverage->amount) {
                $coverage->amount = $orgList[$coverage->coverageCode]->amount ?? '';
            }
            $coverage->quantity = $orgList[$coverage->coverageCode]->quantity ?? '';
            $coverage->unitAmount = $orgList[$coverage->coverageCode]->unitAmount ?? '';
            //服务次数回写
            $coverage->serviceTimes = $orgList[$coverage->coverageCode]->serviceTimes ?? '';
        }

    }

    private function setNonCarInfo($data)
    {
        $printer = new NonCarInquiryPrinter();
        $single = new NonCarInquirySinglePrinter();
        $single->productCode = $this->productCode;
        $single->planCode = $this->planCode;
        $single->inquiryNo = $data['subpolicyno'] ?? '';
        $printer->noCarInquirySingleAppend($single);
        $printer->totalPremium = $data['trialpremium'] ?? '0';
        $this->printer->nonCarInquiryPrinter = $printer;
    }
}
